﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Clarendon.AzureBilling.Library
{
    /// <summary>
    /// Parses a service response 
    /// </summary>
    public class XmlParseServiceProperties : IParseResponseXmlServices
    {
        public T ParseXmlString<T>(string xml)
        {
            XDocument document = XDocument.Parse(xml, LoadOptions.None);

            Trace.WriteLine("Parsing XML response and interpreting <HostedServices/> nodes");
            var services = (from item in document.Descendants(QueryManager.BuildDefaultNamespaceXmlEntity("HostedService"))
                            select new HostedService()
                            {
                                Name = (string)item.Element(QueryManager.BuildDefaultNamespaceXmlEntity("ServiceName")),
                                Url = (string)item.Element(QueryManager.BuildDefaultNamespaceXmlEntity("Url")),
                                AffinityGroup = (string)item.Element(QueryManager.BuildDefaultNamespaceXmlEntity("HostedServiceProperties")).Element(QueryManager.BuildDefaultNamespaceXmlEntity("AffinityGroup")),
                                Description = (string)item.Element(QueryManager.BuildDefaultNamespaceXmlEntity("HostedServiceProperties")).Element(QueryManager.BuildDefaultNamespaceXmlEntity("Description")),
                                Location = (string)item.Element(QueryManager.BuildDefaultNamespaceXmlEntity("HostedServiceProperties")).Element(QueryManager.BuildDefaultNamespaceXmlEntity("Location")),
                                Deployments = (from deployment in item.Descendants(QueryManager.BuildDefaultNamespaceXmlEntity("Deployments"))
                                              select new Deployment()
                                                         {
                                                             Name = (string)deployment.Element(QueryManager.BuildDefaultNamespaceXmlEntity("Deployment")).Element(QueryManager.BuildDefaultNamespaceXmlEntity("Name"))
                                                         }).ToList()
                            }).FirstOrDefault();
            Trace.WriteLine("Finished parsing XML response and interpreted <HostedServices/> nodes");
            return (T)(object)services;
        }
    }
}
